package com.free.semantic.core.service.impl;

import com.free.semantic.common.RelationItem;
import com.free.semantic.core.FunctionProvider;
import com.free.semantic.core.RelationFunction;
import com.free.semantic.core.businessfunction.BasicFunction;
import com.free.semantic.core.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class FunctionProviderImpl implements FunctionProvider, ApplicationContextAware {

    private Map<String, BasicFunction> functionMap;

    @Override
    public RelationFunction getFunction(RelationItem relationItem) {
        String str = utils.getUniqStr(relationItem.getSourceObjectList(), relationItem.getDestObject());
        if (functionMap.containsKey(str)) {
            return convert(functionMap.get(str), relationItem);
        }
        throw new RuntimeException(String.format("不存在 %s的关系", str));
    }

    private RelationFunction convert(BasicFunction basicFunction, RelationItem relationItem) {
        return basicFunction::calculate;
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        Map<String, BasicFunction> beansOfType = context.getBeansOfType(BasicFunction.class);
        functionMap = beansOfType.values().stream().collect(Collectors
            .toMap(function -> utils.getUniqStr(function.require(), function.provider()), Function.identity()));
    }

}
